import React, { PureComponent } from 'react';
import { Responsive, WidthProvider } from 'react-grid-layout';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { PageLoading } from '@ant-design/pro-layout';
import 'antd/dist/antd.css';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

import EchartsGauge from './EchartsGauge';
import EchartsPie from './EchartsPie';
import EchartsBar from './EchartsBar';
import ChartTextArea from './ChartTextArea';
import ChartTextLabel from './ChartTextLabel';
import EchartsLine from './EchartsLine';

import styles from './ChartCard.less';
import './index.less';

const ResponsiveReactGridLayout = WidthProvider(Responsive);

class Dashboard extends PureComponent {

  static defaultProps = {
    cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 },
    rowHeight: 20,
  };

  constructor(props) {
    super(props);
    // const originalLayouts = storageUtils.getFromLS(this.props.dashboardRootOrd) || {};
    const originalLayouts = this.props.layouts || {};
    this.props.loading = undefined;
    this.state = {
      layouts: originalLayouts,
      widgets:[]
    }
  }

  onLayoutChange = (layout, layouts) => {
    const { loading, dispatch, dashboardRootOrd, layoutLock } = this.props;
    if(loading === false) {
      if(!layoutLock) {
        layouts.timestamp = new Date().getTime();
        // storageUtils.saveToLS(dashboardRootOrd, layouts);
        dispatch({ type: 'dashboard/setLayouts', payload: { dashboardRootOrd, layouts } });
        this.setState({ layouts });
      }
    }
  }

  generateDOM = () => {
    return this.state.widgets.map((widget, index) => {
      return (
        <div key={widget.i} data-grid={widget} className={styles.card}>
          {widget.e}
          <span className={`${styles.corner} ${styles.topLeft}`}></span>
          <span className={`${styles.corner} ${styles.topRight}`}></span>
          <span className={`${styles.corner} ${styles.bottomLeft}`}></span>
          <span className={`${styles.corner} ${styles.bottomRight}`}></span>
        </div>
      );
    });
  };

  buildEchart = (chart) => {
    let dom = false;
    const { $typeSpec } = chart.getType();
    if($typeSpec === 'ibmsSupervisor:Gauge') { //仪表盘
      dom = (<EchartsGauge ord={chart.getOrd()} title={chart.getTitle()} fontSize={chart.getFontSize()} min={chart.getMin()} max={chart.getMax()} unit={chart.getUnit()}/>);
    } else if($typeSpec === 'ibmsSupervisor:PieGroup') {
      const legends = [], data = [];
      chart.getNNavChildren().forEach((item)=>{
        const ord = item.getNOrd();
        if(ord !== 'null') {
          legends.push(item.getTitle());
          data.push({name: item.getTitle(), value: 0, ord: ord, fontSize: item.getFontSize()});
        }
      });
      dom = (<EchartsPie title={chart.getTitle()} fontSize={chart.getFontSize()} legends={legends} data={data} ring={chart.getRing()}/>);
    } else if($typeSpec === 'ibmsSupervisor:BarGroup') {
      const legends = [], data = [];
      chart.getNNavChildren().forEach((item)=>{
        const ord = item.getNOrd();
        if(ord !== 'null') {
          legends.push(item.getTitle());
          data.push({name: item.getTitle(), value: 0, ord: ord, fontSize: item.getFontSize()});
        }
      });
      dom = (<EchartsBar title={chart.getTitle()} fontSize={chart.getFontSize()} legends={legends} data={data}/>);
    } else if($typeSpec === 'ibmsSupervisor:TextArea') {
      dom = (<ChartTextArea title={chart.getTitle()} fontSize={chart.getFontSize()} imageSrc={chart.getNImage().replace('file:^', '/file/')} content={chart.getContent()}/>);
    } else if($typeSpec === 'ibmsSupervisor:TextLabel') {
      dom = (<ChartTextLabel ord={chart.getOrd()} title={chart.getTitle()} fontSize={chart.getFontSize()} imageSrc={chart.getNTextIcon().replace('file:^', '/file/')} unit={chart.getUnit()}/>);
    } else if($typeSpec === 'ibmsSupervisor:HistoryLine') {
      const datas = chart.historyList.map((arr)=>arr.map((data)=>([data.time, data.value])));
      dom = (<EchartsLine title={chart.getTitle()} fontColor='white' legends={chart.historyName} datas={datas}/>)
    }
    return dom;
  }

  componentWillReceiveProps(nextProps) {
    if(!nextProps.loading) {
      const { charts } = nextProps;
      const widgets = [];
      let count = 0;
      charts.forEach((chart)=> {
        if(typeof chart.getOrd === 'undefined' || chart.getOrd() !== 'null') {
          const echart = this.buildEchart(chart);
          widgets.push({
            x: (count++ * 3) % 12,
            y: 0,
            w: 3,
            h: 15,
            i: count,
            e: echart,
            t: chart.getTitle()
          });
        }
      });
      const state = {widgets};
      if(nextProps.layouts && nextProps.layouts !== '{}') {
        const ls = JSON.parse(nextProps.layouts) || {};
        if(ls && ls['layouts']) {
          state.layouts = ls['layouts'];
        }
      }
      this.setState(state);
    }
  }

  componentDidMount() {
    const {dispatch, dashboardRootOrd} = this.props;
    dispatch({type: 'dashboard/fetch', payload: {dashboardRootOrd}});
  }

  componentWillUnmount() {
    this.props.dispatch({type: 'dashboard/clearAll'});
  }

  render() {
    const { loading, layoutLock } = this.props;
    if(loading) {
      return <PageLoading/>;
    }
    return (
      <ResponsiveReactGridLayout
        className='layout'
        isDraggable={!layoutLock}
        isResizable={!layoutLock}
        {...this.props}
        layouts={this.state.layouts}
        onLayoutChange={this.onLayoutChange}
      >
        {this.generateDOM()}
      </ResponsiveReactGridLayout>
    )
  }
}

Dashboard.propTypes = {
  dashboardRootOrd: PropTypes.string.isRequired,
}

export default connect(({ dashboard, loading }) => ({
  ...dashboard,
  loading: loading.effects['dashboard/fetch'],
}))(Dashboard);
